﻿using BlogEngine.Gallery.Data;
using BlogEngine.Gallery.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace BlogEngine.Gallery.Controllers
{
    public class ReviewController : ApiController
    {
        public IEnumerable<Review> Get(string pkgId)
        {
            return Repository.GetPackages().Where(p => p.Id == pkgId).FirstOrDefault().Reviews;
        }

        public string Put(string pkgId, [FromBody]Review review)
        {
            var pkg = Repository.GetPackage(pkgId);

            Exception ex = new ApplicationException("In the review controller");
            Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));

            if (pkg != null)
            {
                var x = Request.RequestUri.ToString();

                review.Ip = GetIPAddress();
                review.DatePosted = DateTime.Now;

                if (review.Rating < 1) review.Rating = 1;
                if (review.Rating > 5) review.Rating = 5;

                foreach (var r in pkg.Reviews)
                {
                    if (r.Ip == review.Ip && r.Name == review.Name)
                    {
                        return "You already rated this item";
                    }
                }

                try
                {
                    pkg.Reviews.Add(review);
                    Repository.SavePackage(pkg);
                    return "";
                }
                catch (Exception)
                {
                    return "Error serializing review";
                }
            }

            return "Package not found";
        }

        protected string GetIPAddress()
        {
            //return new Random().Next(1, 100).ToString();

            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }

    }
}
